package com.bmw.redis3.service.impl;

import com.bmw.redis3.base.BaseResponse;
import com.bmw.redis3.base.ClickRequest;
import com.bmw.redis3.dao.ArticleDao;
import com.bmw.redis3.model.Article;
import com.bmw.redis3.service.ClickService;
import com.bmw.redis3.util.ErrorMessage;
import com.bmw.redis3.util.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Classname: ClickServiceImpl
 * Package: com.bmw.redis3.service.impl
 * Description:
 *
 * @Author 王少伟
 * @Create 2024/5/24 23:31
 * @Version 1.8
 */
@Service("clickService")
public class ClickServiceImpl implements ClickService {
    @Autowired
    ArticleDao articleDao;
    @Autowired
    RedisUtil redisUtil;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse click(ClickRequest req) {

        Article demo = articleDao.selectByArticleName(req.getArticleName());
        if (demo == null){
            return BaseResponse.error(ErrorMessage.MESSAGE_NOT_EXIST);
        }
        Article article1 = new Article();
        article1.setArticleId(demo.getArticleId());
        article1.setArticleName(req.getArticleName());
        article1.setContent(demo.getContent());
        article1.setVisits(demo.getVisits() + 1);
        int i = articleDao.updateByPrimaryKeySelective(article1);
        if(i > 0){
            //更新缓存中的排行榜数据
            String key = "rank:list";
            redisUtil.zincrby(key,String.valueOf(req.getArticleName()),article1.getVisits());

        }
        return BaseResponse.OK;
    }

}
